﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace Common.Extension
{
    /// <summary>
    /// 字典扩展
    /// </summary>
    public static class DictionaryExtensions
    {
        /// <summary>
        /// 克隆字典（浅表克隆）
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static IDictionary<TKey, TValue> Clone<TKey, TValue>(this IDictionary<TKey, TValue> source)
        {
            if (source == null)
            {
                return source;
            }
            var typeOfDict = source.GetType();
            var target = (IDictionary<TKey, TValue>)Activator.CreateInstance(typeOfDict);
            foreach (var item in source)
            {
                target.Add(Clone(item.Key), Clone(item.Value));
            }
            return target;
        }
        private static T Clone<T>(T ins)
        {
            try
            {
                if (ins == null)
                {
                    return ins;
                }
                return ins is ICloneable cloneable ? (T)cloneable.Clone() : ins;
            }
            catch
            {
                return ins;
            }
        }

        /// <summary>
        /// 克隆字典（浅表克隆）
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="source"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        public static IDictionary<TKey, TValue> CopyTo<TKey, TValue>(this IDictionary<TKey, TValue> source, IDictionary<TKey, TValue> target)
        {
            if(source == null)
            {
                return null;
            }
            var cloneDict = source.Clone();
            if (target == null)
            {
                return cloneDict;
            }
            foreach (var item in cloneDict)
            {
                target.Add(item.Key, item.Value);
            }
            return target;
        }
    }
}
